<template>
  <div class="top-nav-container">
    <div class="nav-content">
      <!-- 左侧导航菜单 - 固定部分 -->
      <div class="left-menu">
        <el-menu
            mode="horizontal"
            background-color="transparent"
            text-color="#fff"
            active-text-color="#FFF9C4"
            :default-active="activeIndex"
            @select="handleSelect"
        >
          <el-menu-item index="1">
            <i class="el-icon-s-home"></i>
            <span>首页</span>
          </el-menu-item>
          <el-menu-item index="4">
            <i class="el-icon-info"></i>
            <span>关于我们</span>
          </el-menu-item>
        </el-menu>
      </div>

      <!-- 右侧区域 - 动态内容 -->
      <div class="right-content">
        <!-- 未登录状态 -->
        <div v-if="!isLoggedIn" class="auth-buttons">
          <el-button
              type="text"
              icon="el-icon-user"
              @click="showLoginDialog = true"
          >
            登录
          </el-button>
          <el-button
              type="text"
              icon="el-icon-user-solid"
              @click="showRegisterDialog = true"
          >
            注册
          </el-button>
        </div>

        <!-- 已登录状态 -->
        <div v-else class="user-info">
          <el-dropdown
              trigger="click"
              @command="handleCommand"
              :append-to-body="true"
          >
            <div class="user-profile">
              <el-avatar :size="36" :src="user.avatarUrl || defaultAvatar" />
              <span class="username">{{ user.username }}</span>
              <i class="el-icon-caret-bottom"></i>
            </div>
            <template #dropdown>
              <el-dropdown-menu class="user-dropdown-menu">
                <el-dropdown-item command="profile">
                  <i class="el-icon-user"></i>个人中心
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  <i class="el-icon-switch-button"></i>退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </div>

    <BaseUserLogin
        v-model="showLoginDialog"
        @login-success="handleLoginSuccess"
        @open-register="showRegisterDialog = true"
    />
    <BaseUserRegister
        v-model="showRegisterDialog"
        @register-success="handleRegisterSuccess"
        @open-login="showLoginDialog = true"
    />
    <!-- 新手指引弹窗 -->
    <NewUserGuide
        v-model="guideVisible"
        :isPageMode="false"
        @guide-complete="handleGuideComplete"
    />
  </div>
</template>

<script>
import BaseUserRegister from "@/views/register/BaseUserRegister.vue";
import BaseUserLogin from "@/views/login/BaseUserLogin.vue";
import NewUserGuide from "@/views/Guide/NewUserGuide.vue";
import { ElMessage } from "element-plus";

export default {
  components: {
    BaseUserRegister,
    BaseUserLogin,
    NewUserGuide
  },
  data() {
    return {
      activeIndex: "1",
      showRegisterDialog: false,
      showLoginDialog: false,
      isLoggedIn: false,
      guideVisible: false,
      user: {
        userId: null,
        username: "",
        avatarUrl: "",
        userType: 0
      },
      defaultAvatar: require("@/assets/images/default-avatar.png"),
      // 用户类型路由映射
      userTypeRoutes: {
        1: "/elderly/home",       // 老人
        2: "/family/home",        // 家属
        3: "/volunteer",     // 志愿者
        4: "/staff/home",         // 服务人员
        5: "/doctor/home",        // 医生
        6: "/admin",    // 区域管理员
        7: "/admin",         // 普通管理员
        8: "/admin"    // 超级管理员
      }
    };
  },
  mounted() {
    this.checkLoginStatus();
    window.addEventListener('storage', this.handleStorageChange);
  },
  beforeDestroy() {
    window.removeEventListener('storage', this.handleStorageChange);
  },
  methods: {
    checkLoginStatus() {
      const userData = localStorage.getItem("user");
      const token = localStorage.getItem("token");

      if (userData && token) {
        try {
          this.user = JSON.parse(userData);
          this.isLoggedIn = true;

          if (typeof this.user.userType === 'undefined') {
            this.user.userType = 0;
          }
        } catch (e) {
          console.error("用户数据解析失败", e);
          this.isLoggedIn = false;
        }
      } else {
        this.isLoggedIn = false;
        this.user = { username: "", avatarUrl: "", userType: 0 };
      }
    },
    handleStorageChange(event) {
      if (event.key === "user" || event.key === "token") {
        this.checkLoginStatus();
      }
    },
    handleSelect(index) {
      switch (index) {
        case "1":
          this.$router.push("/");
          break;
        case "4":
          this.$router.push("/about");
          break;
      }
    },
    handleCommand(command) {
      if (command === "logout") {
        this.logout();
      } else if (command === "profile") {
        this.navigateToProfile();
      }
    },
    // 个人中心导航
    navigateToProfile() {
      if (this.user.userType === 0) {
        this.guideVisible = true;
        ElMessage.info('请先完成身份选择以访问个人中心');
      } else {
        const route = this.userTypeRoutes[this.user.userType];
        if (route) {
          this.$router.push(route);
        } else {
          ElMessage.warning('未找到匹配的用户类型路由');
        }
      }
    },
    logout() {
      localStorage.removeItem("user");
      localStorage.removeItem("token");
      this.isLoggedIn = false;
      this.user = { username: "", avatarUrl: "", userType: 0 };
      this.$message.success("已成功退出登录");
      this.$router.push("/");
    },
    // 处理登录成功事件
    handleLoginSuccess(userData) {
      try {
        const user = userData?.user || userData;
        if (!user.username) throw new Error("无效用户数据");

        this.showLoginDialog = false;
        this.isLoggedIn = true;

        this.user = {
          userId: user.userId,
          username: user.username,
          avatarUrl: user.avatarUrl || this.defaultAvatar,
          userType: user.userType || 0
        };

        localStorage.setItem('user', JSON.stringify(this.user));

        if (this.user.userType === 0) {
          this.guideVisible = true;
          ElMessage.info('请完成新手指引以继续使用平台');
        }
      } catch (error) {
        console.error("登录成功处理异常:", error);
        this.$message.error("登录状态异常，请重新登录");
        this.logout();
      }
    },
    // 处理新手指引完成事件
    handleGuideComplete() {
      this.guideVisible = false;
      this.checkLoginStatus();
      this.$message.success('新手指引已完成，欢迎使用智慧养老平台！');
    },
    handleRegisterSuccess(userData) {
      this.showRegisterDialog = false;
      this.isLoggedIn = true;
      this.user = userData.user;
      this.user.userType = this.user.userType || 0;
      localStorage.setItem('user', JSON.stringify(this.user));
      this.$message.success(`注册成功，欢迎${this.user.username}！`);
    }
  }
};
</script>

<style scoped>
/* 顶部导航栏容器 - 蓝色主题 */
.top-nav-container {
  background-color: #409EFF; /* 蓝色主题 */
  color: white;
  height: 60px;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  font-family: "Microsoft YaHei", "微软雅黑", sans-serif;
}

.nav-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  max-width: 1200px;
  height: 100%;
  margin: 0 auto;
  padding: 0 20px;
}

.left-menu {
  flex: 1;
}

.right-content {
  display: flex;
  align-items: center;
  min-width: 200px;
  justify-content: flex-end;
}

/* 登录注册按钮样式 */
.auth-buttons {
  display: flex;
  gap: 10px;
}

.auth-buttons .el-button {
  color: white !important;
  font-size: 16px;
  padding: 0 15px;
}

.auth-buttons .el-button:hover {
  color: #FFF9C4 !important;
  background: rgba(255, 255, 255, 0.15);
}

/* 用户信息样式 */
.user-info {
  cursor: pointer;
}

.user-profile {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 30px;
  transition: all 0.3s;
  background-color: rgba(255, 255, 255, 0.15);
}

.user-profile:hover {
  background-color: rgba(255, 255, 255, 0.25);
}

.username {
  font-size: 16px;
  color: #fff;
  font-weight: 500;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 菜单激活状态指示器 */
.left-menu .el-menu-item.is-active {
  border-bottom: 3px solid #FFF9C4 !important;
  font-weight: bold;
}

/* 左侧菜单项样式 */
.left-menu .el-menu-item {
  margin-right: 10px;
  border-radius: 4px;
  height: 60px;
  line-height: 60px;
}

/* 移除菜单背景色 */
.left-menu .el-menu {
  background-color: transparent !important;
}

.left-menu .el-menu--horizontal {
  border-bottom: none !important;
}
</style>

<!-- 全局样式修复 -->
<style>
/* 下拉菜单项样式 */
.el-dropdown-menu__item {
  font-size: 16px !important;
  padding: 12px 20px !important;
  color: #606266 !important;
}

.el-dropdown-menu__item:hover {
  background-color: #ecf5ff !important;
  color: #409EFF !important;
}

/* 下拉菜单图标样式 */
.el-dropdown-menu__item i {
  color: #409EFF;
  margin-right: 10px;
  font-size: 16px;
}

/* 头像样式 */
.el-avatar {
  border: 2px solid rgba(255, 255, 255, 0.3);
  background-color: #FFF;
}

/* 确保下拉菜单不被遮挡 */
.el-popper {
  z-index: 9999 !important;
}

/* 按钮文字颜色修正 */
.el-button--text {
  color: white;
}
</style>